﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Syndication;

namespace SKB.Controllers
{
    public class PostsController : Controller
    {
        //
        // GET: /Posts/
        private SKBEntities model = new SKBEntities();
        private const int PostsPerPage = 4;
        private const int PostsPerFeed = 25;


        public ActionResult RSS()
        {
            IEnumerable<SyndicationItem> posts =
                (from post in model.Posts
                 where post.DateTime < DateTime.Now
                 orderby post.DateTime descending
                 select post).Take(PostsPerFeed).ToList().Select(x => GetSyndicationItem(x));

            string url = "http://http://www.danielkondos.com/Posts";
            Uri uri = new Uri(url);
            SyndicationFeed feed = new SyndicationFeed("Daniel P. Kondos", "Daniel P. Kondos Blog", uri, posts);
            Rss20FeedFormatter formattedFeed = new Rss20FeedFormatter(feed);
            return new FeedResult(formattedFeed);
        }

        private SyndicationItem GetSyndicationItem(Post post)
        {
            string url = "http://http://www.danielkondos.com/Posts/Details/" + post.ID;
            Uri uri = new Uri(url);
            return new SyndicationItem(post.Title, post.Body, uri);
        }

        public ActionResult Tags(string id)
        {
            ViewBag.IsAdmin = IsAdmin;
            Tag tag = GetTag(id);
            return View("Index", tag.Posts);

        }

        public ActionResult Delete(int id)
        {
            if (IsAdmin)
            {
                Post post = GetPost(id);
                model.DeleteObject(post);
                model.SaveChanges();
            }
            return RedirectToAction("Index");
        }

        public ActionResult DeleteComment(int id)
        {
            if (IsAdmin)
            {
                Comment comment = GetComment(id);
                model.DeleteObject(comment);
                model.SaveChanges();
            }
            return RedirectToAction("Index");
        }

        [ValidateInput(false)]
        public ActionResult Comment(int id, string name, string email, string body)
        {
            Post post = GetPost(id);
            Comment comment = new Comment()
            {
                Post = post,
                DateTime = DateTime.Now,
                Name = name,
                Email = email,
                Body = body
            };

            model.AddToComments(comment);
            model.SaveChanges();

            return RedirectToAction("Details", new { id = id });
        }

        public ActionResult Details(int id)
        {
            Post post = GetPost(id);
            ViewBag.IsAdmin = IsAdmin;
            return View(post);
        }

        public ActionResult Index(int ? id)
        {
            int pageNumber = id ?? 0;

            IEnumerable<Post> posts =
                (from post in model.Posts
                where post.DateTime < DateTime.Now
                orderby post.DateTime descending
                 select post).Skip(pageNumber * PostsPerPage).Take(PostsPerPage + 1);

            ViewBag.IsPreviousPageLinkVisible = pageNumber > 0;
            ViewBag.IsNextPageLinksVisible = posts.Count() > PostsPerPage;
            ViewBag.IsAdmin = IsAdmin;
            ViewBag.PageNumber = pageNumber;
            return View(posts.Take(PostsPerPage));
        }

        [ValidateInput(false)]
        public ActionResult Update(int? id, string title, string body, string imageURL, DateTime dateTime, string tags)
        {
            if (!IsAdmin)
            {
                RedirectToAction("Index");
            }

            Post post = GetPost(id);
            post.Title = title;
            post.Body = body;
            post.ImageURL = imageURL;
            post.DateTime = dateTime;
            post.Tags.Clear();
            tags = tags ?? string.Empty;
            string[] tagNames = tags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string tagName in tagNames)
            {
                post.Tags.Add(GetTag(tagName));
            }

            if (!id.HasValue)
            {
                model.AddToPosts(post);
            }

            model.SaveChanges();
            return RedirectToAction("Details", new { id = post.ID });

        }

        public ActionResult Edit(int? id)
        {
            Post post = GetPost(id);
            StringBuilder tagList = new StringBuilder();

            foreach (Tag tag in post.Tags)
            {
                tagList.AppendFormat("{0} ", tag.Name);
            }
            ViewBag.Tags = tagList.ToString();
            return View(post);
        }

        private Tag GetTag(string tagName)
        {
            return model.Tags.Where(x => x.Name == tagName).FirstOrDefault() ?? new Tag() { Name = tagName };
        }

        private Post GetPost(int? id)
        {
            return id.HasValue ? model.Posts.Where(x => x.ID == id).First() : new Post() { ID = -1 };
        }

        private Comment GetComment(int? id)
        {
            return model.Comments.Where(x => x.ID == id).First();
        }

        //TODO: dont just return true
        public bool IsAdmin 
        {
            get
            {
                return ( Session["IsAdmin"] != null && (bool)Session["IsAdmin"]);
                //return (true /*Session["IsAdmin"] != null && (bool)Session["IsAdmin"]*/);
            }
        }
    }
}
